/*
 * @lc app=leetcode id=148 lang=cpp
 *
 * [148] Sort List
 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if (!head || !head->next) {
            return head;
        }

        ListNode *fast = head;
        ListNode *slow = head;

        while (fast) {
            slow = slow->next;
            fast = fast->next;
            if (fast) {
                fast = fast->next;
            }
        }

        ListNode *l = head;
        ListNode *r = slow->next;
        slow->next  = NULL;

        return mergeList(l, r);
    }

    ListNode *mergeList(ListNode *n1, ListNode *n2) {
        ListNode *head = NULL;
        ListNode *node = NULL;
        ListNode *cur  = NULL;

        while (n1 && n2) {
            if (n1->val < n2->val) {
                cur = n1;
                n1 = n1->next;
            } else {
                cur = n2;
                n2 = n2->next;
            }

            if (!head) {
                head = cur;
                node = head;
            } else {
                node->next = cur;
                node = cur;
            }
        }

        if (n1) {
            node->next = n1;
        } else if (n2) {
            node->next = n2;
        }

        return head;
    }
};

